import { List, Image, InfiniteScroll } from "antd-mobile"
import { useEffect, useState } from "react"
import { articleGetArticleListService } from "@/api/article"
import { useNavigate } from "react-router-dom"


type Props = {
  channel_id:string
}
const HomeList = (props:Props) => {
  const naivgate = useNavigate()
  const [listRes, setListRes] = useState<Api.Article.GetArticleListRes>({
    results: [],
    pre_timestamp: '' + new Date().getTime()
  })
  const [articleList, setArticleList] = useState<Api.Article.ArticleItem[]>([])
  const [hasMore, setHasMore] = useState(true)
  const loadMore = async () => {
    try {
      const res = await articleGetArticleListService({
        channel_id:props.channel_id,
        timestamp: listRes.pre_timestamp
      })
      if(res.data.data.results.length === 0) {
        console.log('no more data')
        setHasMore(false)
      }
      setListRes({results:[...listRes.results, ...res.data.data.results], pre_timestamp: res.data.data.pre_timestamp})
      setArticleList([...listRes.results, ...res.data.data.results])
    }catch(e) {
      throw new Error('fetch articleList failed')
    }
  }
  useEffect(() => {
    const fetchArticleList = async () => {
      try {
        const res = await articleGetArticleListService({
          channel_id:props.channel_id,
          timestamp:'' + new Date().getTime()
        })
        setListRes(res.data.data)
        setArticleList(res.data.data.results)
      }catch(e) {
        throw new Error('fetch articleList failed')
      }
    }
    fetchArticleList()
  }, [props.channel_id])
  return (
    <>
      <List>
      {articleList?.map((item) => (
        <List.Item
          key={item.art_id}
          prefix={
            <Image
              src={item.cover.images?.[0]}
              style={{ borderRadius: 20 }}
              fit="cover"
              width={40}
              height={40}
            />
          }
          description={item.pubdate}
          onClick={() => naivgate(`/detail?id=${item.art_id}`)}
          >
          {item.title}
        </List.Item>
      ))}
    </List>
    <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10}></InfiniteScroll>
  </>
  )
}

export default HomeList